import os
import collections
from tabulate import tabulate

# 需要先执行 pip install tabulate 安装软件包


def count_lines_and_chars(file_path) -> tuple[int, int]:
    with open(file_path, "r", encoding="utf-8") as file:
        lines = file.readlines()
        num_lines = len(lines)
        num_chars = sum(len(line) for line in lines)
    return num_lines, num_chars



def main():
    # 修改为接收路径数组
    src_dirs = ["./WebBackend", "./WebFrontend"]  # 可以添加更多目录
    
    file_types = {
        "vue": [],  # 存储vue文件的路径
        "t/js": [],  # 存储ts/js文件的路径
        "s/css": [],  # 存储css scss sass文件的路径
        "py": [],   # 存储py文件的路径
    }

    # 遍历所有目录
    for src_dir in src_dirs:
        for root, dirs, files in os.walk(src_dir):
            for file in files:
                if file.endswith(".vue"):
                    file_types["vue"].append(os.path.join(root, file))
                elif file.endswith(".ts") or file.endswith(".js"):
                    file_types["t/js"].append(os.path.join(root, file))
                elif (
                    file.endswith(".css")
                    or file.endswith(".scss")
                    or file.endswith(".sass")
                ):
                    file_types["s/css"].append(os.path.join(root, file))
                elif file.endswith(".py"):
                    file_types["py"].append(os.path.join(root, file))
    
    # 统计文件数量、合计行数和合计字符数
    stats = collections.defaultdict(lambda: [0, 0, 0])
    # [文件数量, 合计行数, 合计字符数]
    for file_type, file_list in file_types.items():
        stats[file_type][0] = len(file_list)  # 文件数量
        for file_path in file_list:
            num_lines, num_chars = count_lines_and_chars(file_path)
            stats[file_type][1] += num_lines  # 合计行数
            stats[file_type][2] += num_chars  # 合计字符数

    # 准备表格数据
    table_data = []
    for file_type, stats_values in stats.items():
        num_files, total_lines, total_chars = stats_values
        table_data.append([file_type, num_files, total_lines, total_chars])

    # 输出统计结果
    print("文件统计结果：")
    print( #打印表格
        tabulate(
            table_data, headers=["Type", "Files", "Lines", "Chars"], tablefmt="grid"
        )
    )
    print("总行数:", sum(stats[key][1] for key in stats))
    print("总字符数:", sum(stats[key][2] for key in stats))
    print("统计的目录:", ", ".join(src_dirs))


if __name__ == "__main__":
    main()